package com.zhanghe.study.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

import java.nio.charset.StandardCharsets;

/**
 * 客户端处理器
 * @author zh
 * @date 2020/12/2 11:33
 */
public class ClientHandler extends ChannelInboundHandlerAdapter {

    // 通道准备就绪
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 写数据
        ctx.writeAndFlush(Unpooled.copiedBuffer("你好呀".getBytes()));
    }

    // 读取服务器的消息数据
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try{
            ByteBuf buf = (ByteBuf) msg;
            byte[] data = new byte[buf.readableBytes()];
            buf.readBytes(data);
            String request = new String(data, StandardCharsets.UTF_8);
            System.out.println("接收到的回复为：->"+request);

        } finally {
            // 释放缓冲
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
